//管理用户感知/在线状态功能


export const setupAwareness = (awareness, userId, username) => {
  // 设置当前用户信息
  updateUserInfo(awareness, userId, username);
  
  // 返回API
  return {
    updateUserInfo: (newUsername) => updateUserInfo(awareness, userId, newUsername),
    updateCursorPosition: (x, y) => updateCursorPosition(awareness, userId, x, y),
    updateSelectedObject: (objectId) => updateSelectedObject(awareness, userId, objectId),
    getOnlineUsers: () => getOnlineUsers(awareness),
    getSelectedObjects: () => getSelectedObjects(awareness)
  };
};

/**
 * 更新当前用户信息
 */
const updateUserInfo = (awareness, userId, username) => {
  const color = getColorForUser(userId);
  
  awareness.setLocalStateField('user', {
    id: userId,
    name: username,
    color
  });
};

/**
 * 更新光标位置
 */
const updateCursorPosition = (awareness, userId, x, y) => {
  const currentState = awareness.getLocalState() || {};
  
  awareness.setLocalStateField('user', {
    ...currentState.user,
    cursor: { x, y }
  });
};

/**
 * 更新选中的对象
 */
const updateSelectedObject = (awareness, userId, objectId) => {
  const currentState = awareness.getLocalState() || {};
  
  awareness.setLocalStateField('user', {
    ...currentState.user,
    selectedObject: objectId
  });
};

/**
 * 获取所有在线用户
 */
const getOnlineUsers = (awareness) => {
  const users = [];
  awareness.getStates().forEach((state, clientId) => {
    if (state.user) {
      users.push({
        clientId,
        ...state.user
      });
    }
  });
  return users;
};

/**
 * 获取所有用户选中的对象
 */
const getSelectedObjects = (awareness) => {
  const selectedObjects = [];
  awareness.getStates().forEach((state, clientId) => {
    if (state.user && state.user.selectedObject) {
      selectedObjects.push({
        clientId,
        userId: state.user.id,
        username: state.user.name,
        objectId: state.user.selectedObject
      });
    }
  });
  return selectedObjects;
};

/**
 * 为用户生成一致的颜色
 */
const getColorForUser = (userId) => {
  const colors = [
    '#f44336', '#e91e63', '#9c27b0', '#673ab7', 
    '#3f51b5', '#2196f3', '#03a9f4', '#00bcd4',
    '#009688', '#4caf50', '#8bc34a', '#cddc39'
  ];
  
  // 简单的哈希函数，确保同一用户ID总是获得相同颜色
  let hash = 0;
  for (let i = 0; i < userId.length; i++) {
    hash = ((hash << 5) - hash) + userId.charCodeAt(i);
    hash |= 0; // 转换为32位整数
  }
  
  // 使用绝对值并取模获取颜色索引
  const index = Math.abs(hash) % colors.length;
  return colors[index];
};